import React, { Component, Fragment } from 'react'
import { Upload, Form, Input, Button, Table, Row, Col, Pagination, message } from 'antd'
import {
  UploadOutlined,
  ToolOutlined,
  SearchOutlined,
  CloseCircleOutlined,
  RedoOutlined,
} from '@ant-design/icons'

import styles from "./index.module.scss"
import httpUtil from 'utils/request'
class BatchImport extends Component {
  constructor(props) {
    super(props)

    this.state = {
      //复选框数据
      selectedRowKeys: [],
      //搜索关键词
      keyword: '',
      //
      status: 0,
      pageNumber: 1,
      pageSize: 9,
      //   limit: 10,
      total: '',
      //totalOne加载总数时的标志位，设置为1，
      totalOne: 1,
      csvfile: [],
      csvfileList: 11,
      adminId: [],
      //表头
      columns: [
        {
          title: '用户ID',
          dataIndex: 'userId',
          key: 'userId',
        },
        {
          title: '用户名',
          dataIndex: 'userName',
          key: 'userName',
        },
        {
          title: '密码',
          dataIndex: 'password',
          key: 'password',
        },
        {
          title: '专业',
          dataIndex: 'major',
          key: 'major',
        },
        {
          title: '班级',
          dataIndex: 'sclass',
          key: 'sclass',
        },
        {
          title: '学号',
          dataIndex: 'sid',
          key: 'sid',
        },
        {
          title: '邮箱',
          dataIndex: 'email',
          key: 'email',
        },
        {
          title: '电话',
          dataIndex: 'tel',
          key: 'tel',
        },
      ],
      //表的数据
      data: [],
    }
  }

  //暂时只能删除没有开始比赛的用户
  onDelete = userId => {
    // console.log(userId)
    // var formdata = new FormData()
    // //可以通过append()方法来追加数据
    // formdata.append('userId', userId)
    httpUtil
      .deletestu({ userId })
      .then(res => {
        if (res.message === '成功') {
          message.success(userId + ' 删除成功')
        } else {
          message.error(res.data + userId + ' 正在比赛')
        }
      }, this.loadData())
      .catch(err => console.log(err))
  }

  //批量删除暂时只能删除没有开始比赛的用户
  onDeleteSome = () => {
    const userIds = this.state.selectedRowKeys.join()
    if (userIds) {
      // httpUtil
      //   .deletestus({ userIds })
      //   .then((res) => {
      //     if (res.message === '成功') {
      //       message.success('批量删除成功')
      //     } else {
      //       message.error('有用户正在比赛，批量删除失败！')
      //     }
      //   }, this.loadData())
      //   .catch((err) => console.log(err))
    } else {
      const key = 'updatable'
      setTimeout(() => {
        message.warning({
          content: '请选择需要创建比赛的用户',
          key,
          duration: 2,
        })
      }, 200)
      return false
    }
  }

  //搜索
  onFinish = value => {
    if (value.keyword === undefined || value.keyword === '') {
      message.info('请输入学号查找')
      return false
    }
    var formdata = new FormData()
    //可以通过append()方法来追加数据
    formdata.append('status', this.state.status)
    formdata.append('keyword', value.keyword)
    // formdata.append('limit', this.state.pageSize)
    // formdata.append('startPage', this.state.pageNumber)
    // let _this = this

    httpUtil
      .search(formdata)
      .then(res => {
        const listData = res.data
        if (listData.length === 0) {
          message.info(' ' + value.keyword + '，没有找到 ！')
        } else {
          message.info(value.keyword + '，找到' + listData.length + '条相关数据')
          this.setState({
            data: listData,
            total: 1,
          })
        }
      })
      .catch(err => console.log(err))
  }
  componentDidMount() {
    this.loadData()
  }

  //获取列表数据
  loadData = () => {
    var formdata = new FormData()
    //可以通过append()方法来追加数据
    formdata.append('page', this.state.pageNumber)
    formdata.append('status', this.state.status)
    formdata.append('limit', this.state.pageSize)

    //这里暂时无数据 等导入之后才获取导入的数据

    // httpUtil
    //   .pageUsers(formdata)
    //   .then(res => {
    //     const listData = res.data
    //     if (listData) {
    //       this.setState({
    //         data: listData,
    //       })
    //     }
    //     if (this.state.total === '') {
    //       httpUtil
    //         .findAllApprovedUser()
    //         .then(res => {
    //           const total = res.data.length
    //           if (listData) {
    //             this.setState({
    //               total: total,
    //             })
    //           }
    //         })
    //         .catch(err => console.log(err))
    //     }
    //   })
    //   .catch(err => console.log(err))
  }

  //复选框
  onCheckebox = selectedRowKeys => {
    this.setState({ selectedRowKeys })
  }
  //当前页码
  onChangeCurrnePage = value => {
    console.log(this.state.pageNumber)
    console.log(value)

    this.setState(
      {
        pageNumber: value || 1,
      },
      () => {
        console.log(this.state.pageNumber)

        this.loadData()
      }
    )
  }
  /** 下拉页码 */
  onChangeSizePage = (current, page) => {
    console.log(current)
    this.setState(
      {
        pageNumber: 1,
        pageSize: page,
      },
      () => {
        this.loadData()
      }
    )
  }

  render() {
    const _this = this
    const props = {
      name: 'file',
      action: 'https://www.mocky.io/v2/5cc8019d300000980a055e76',
      headers: {
        authorization: 'authorization-text',
      },
      onChange(info) {
        if (info.file.status === 'done') {
          httpUtil.getTeacherList().then(res => {
            const adminId = res.data[0].adminId
            var formdata = new FormData()
            //可以通过append()方法来追加数据
            formdata.append('csvfile', info.file.originFileObj)
            formdata.append('columns', _this.state.csvfileList)
            formdata.append('adminId', adminId)
            httpUtil
              .importstu(formdata)
              .then(res => {
                if (res.message === '失败') {
                  message.error(`${info.file.name} 文件导入失败，请不要传入重复数据`)
                }
                if (res.message === '成功') {
                  message.success(`${info.file.name} 文件导入成功！`)
                }
              }, _this.loadData())
              .catch(err => console.log(err))
          })
        } else if (info.file.status === 'error') {
          message.error(`${info.file.name} file upload failed.`)
        }
      },
    }

    const { columns, data } = this.state
    const rowSelection = {
      onChange: this.onCheckebox,
    }
    return (
      <Fragment>
        <div className="search-box">
          <Form layout="inline" onFinish={this.onFinish.bind(this)}>
            <Form.Item name="keyword">
              <Input placeholder="请输入学号" />
            </Form.Item>
            <Form.Item shouldUpdate={true}>
              <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
                搜索
              </Button>
            </Form.Item>
          </Form>
        </div>
        <div className="content-box">
          <Table
            pagination={false}
            className="table-wrap"
            rowSelection={rowSelection}
            size="small"
            rowKey="userId"
            columns={columns}
            dataSource={data}
            bordered></Table>
          <Row className={styles["footer-btns"]}>
            <Col span={8}>
              <Button
                type='primary'
                onClick={() => this.onDeleteSome()}
                className={styles["pull-left"]}
                icon={<ToolOutlined />}>
                创建比赛
              </Button>
              <Upload {...props}>
                <Button icon={<UploadOutlined />}>批量导入</Button>
              </Upload>
            </Col>
            <Col span={16}>
              <Pagination
                className={styles["pull-right"]}
                onChange={this.onChangeCurrnePage}
                onShowSizeChange={this.onChangeSizePage}
                hideOnSinglePage={true}
                total={this.state.total}
                showSizeChanger={false}
                showQuickJumper
                defaultCurrent={1}
                showTotal={total => `共 ${total} 条`}
              />
            </Col>
          </Row>
        </div>
      </Fragment>
    )
  }
}

export default BatchImport
